import { useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'

import useGetUserInfo from './useGetUserInfo'

const useNavPage = (waitingData: boolean) => {
  const nav = useNavigate()
  const { pathname } = useLocation()
  const { username } = useGetUserInfo()

  const whiteList = ['/login', '/register', '/']

  useEffect(() => {
    if (waitingData) return

    // 已登录
    if (username && whiteList.includes(pathname)) {
      nav('/manage/list')
    }

    // 未登录
    if (!username && !whiteList.includes(pathname)) {
      nav('/login')
    }
  }, [username, pathname, waitingData])
}

export default useNavPage
